from pattern.circuit import Control


class entry(Control):

    def __init__(self):
        self.channels = { }

    def realize(self, event):
        self.updated(event)

    def incoming(self, event):
        action, channels, user = event.data
        if channels is None:
            channels = self.channels.keys()
        if action == "join":
            self.join(event, channels, user)
        elif action == "part":
            self.part(event, channels, user)

    def please(self, event):
        return self.channels

    def join(self, event, channels, user):
        for channel in channels:
            if channel in self.channels:
                channel_users = self.channels[channel]
            else:
                channel_users = self.channels[channel] = []
            if user not in channel_users:
                channel_users.append(user)
                self.announce(event, channel, user, "JOIN")
        self.updated(event)

    def part(self, event, channels, user):
        for channel in channels:
            if self.channels.has_key(channel):
                if user in self.channels[channel]:
                    self.channels[channel].remove(user)
                    self.announce(event, channel, user, "PART")   
        self.updated(event)

    def updated(self, event):
        bridge = self.acquireInterface(event, "Channels")
        if bridge is not None:
            bridge.push(self)

    def announce(self, event, channel, user, state):
        ANN_TEMPLATE = ":%(user)s!here %(state)s :%(channel)s"
        announcement = ANN_TEMPLATE % vars()
        bridge = self.acquireInterface(event, "announce")
        if bridge is not None:
            bridge.push(channel, announcement)

    def __repr__(self):
        return `self.channels`
